#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<pthread.h>

//读写锁创建

int number = 0;

//定义一把锁
pthread_rwlock_t rwlock;

//写线程回调函数
void *thread_write(void *arr)
{
	int i = *(int *)arr;
	int cur;
	while(1)
	{
		//加写锁
		pthread_rwlock_wrlock(&rwlock);		

		cur = number;
		cur++;
		number = cur;
		printf("[%d]-w:[%d]\n",i,cur);

		//解锁
		pthread_rwlock_unlock(&rwlock);
		usleep(500);
	}
}

//读线程回调函数
void *thread_read(void *arr)
{
	int i = *(int *)arr;
	int cur; 
	while(1)
	{
		//加读锁
		pthread_rwlock_rdlock(&rwlock);

		cur = number;
		printf("[%d]-R:[%d]\n",i,cur);
		
		//解锁
		pthread_rwlock_unlock(&rwlock);
		usleep(400);
	}
}



int main()
{
	//读写锁初始化
	pthread_rwlock_init(&rwlock,NULL);


	int n = 8;
	int i = 0;
	//创建线程--3个写线程－－５个读线程
	pthread_t thread[8];
	int arr[8];
	//char name[64];
	//memset(name,0x00,sizeof(name));
	//３个写线程
	for(i;i<3;i++)
	{
		arr[i] = i;
		int res = pthread_create(&thread[i],NULL,thread_write,&arr[i]);
		if(res < 0)
		{
			printf("thead_create error,[%s]\n",strerror(res));
			return -1;
		}
	}
	for(i=3;i<n;i++)
	{
		arr[i] = i;
		int res = pthread_create(&thread[i],NULL,thread_read,&arr[i]);
		if(res < 0)
		{
			printf("thead_create error,[%s]\n",strerror(res));
			return -1;
		}
	}

	//回收子线程
	for(int j=0;j<n;j++)
	{
		pthread_join(thread[j],NULL);
	}
	
	//释放锁
	pthread_rwlock_destroy(&rwlock);

	return 0;
}
